package com.dwk.controller;

import com.dwk.config.DelayedQueueConfig;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 发送延迟消息
 */

@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //发消息
    @GetMapping("/sendMsg/{message}")
    public String sendMsg(@PathVariable String message) {
        log.info("当前时间:{},发送一条信息给两个TTL队列：{}", new Date().toString(), message);

        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为10秒:" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为40秒:" + message);

        return message;
    }

    //发带有指定过期时间消息
    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public String sendMsg(@PathVariable String message, @PathVariable String ttlTime) {
        log.info("当前时间:{},发送一条时长是{}ms的信息给两个TTL队列：{}", new Date().toString(), ttlTime, message);

        rabbitTemplate.convertAndSend("X", "XC", message, msg -> {
            //设置延迟时长
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });

        return message;
    }


    //基于插件，开始发消息及延迟时间
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public String sendMsg(@PathVariable String message, @PathVariable Integer delayTime) {
        log.info("当前时间:{},发送一条时长是{}ms的信息给延迟队列：{}", new Date().toString(), delayTime, message);

        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY
                , message, msg -> {
                    //设置延迟时长
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                });

        return message;
    }

}
